// Test setup file
const { JSDOM } = require('jsdom');

// Create a DOM environment
const dom = new JSDOM(`
<!DOCTYPE html>
<html>
<head></head>
<body></body>
</html>
`, {
    url: 'https://example.com',
    pretendToBeVisual: true,
    resources: 'usable'
});

// Set up global variables
global.window = dom.window;
global.document = dom.window.document;
global.location = dom.window.location;

// Ensure document.body exists
if (!global.document.body) {
    global.document.body = global.document.createElement('body');
    global.document.documentElement.appendChild(global.document.body);
}

// Mock fetch
global.fetch = (url) => {
    return Promise.resolve({
        ok: true,
        json: () => Promise.resolve({ content: Buffer.from('test content').toString('base64') }),
        text: () => Promise.resolve('test content')
    });
};

// Mock path module
global.path = {
    join: (...args) => args.join('/')
};

// Mock url-join
global.urlJoin = (...args) => args.join('/');

// Mock position-map-text-to-markdown
global.findAllPositions = () => [];

// Mock gitbook
global.window.require = (deps, callback) => {
    if (deps.includes('gitbook')) {
        const mockGitbook = {
            events: {
                bind: (event, handler) => {
                    if (event === 'start') {
                        // Simulate gitbook start event
                        setTimeout(() => {
                            handler({}, {
                                'gitcode-issue-feedback': {
                                    repo: 'test/repo',
                                    label: 'Test Report'
                                }
                            });
                        }, 100);
                    }
                }
            },
            state: {
                config: { root: './' },
                filepath: 'test.md',
                chapterTitle: 'Test Chapter'
            }
        };
        callback(mockGitbook);
    }
};
